from flask import Blueprint, render_template, jsonify, session, redirect, url_for, current_app, request
import json
import time
from app.model.mo_nep_pss import SchichtKalenderGrossAnzeige, \
    ArchivWorkLog, \
    ArchivAKTBDEMA, \
    NG6EINZELEREIGNISSE, \
    NG6OOSEREIGNISSE, \
    StandARDSchichtModelle, \
    StandARDSchichten, \
    StandardModelle, \
    Z6ArchivWorkLog, \
    Z6ArchivAKTBDEMA, \
    SchichtKalender, \
    ArchivWSANBAU, \
    Z6SchichtKalenderGrossAnzeige, \
    Z6NG6OOSEREIGNISSE, \
    Z6NG6EINZELEREIGNISSE, \
    StueckZAHLProSchicht

from app import db, db2
from sqlalchemy import and_, func, distinct, select, desc

module_nep_pss = Blueprint('NEP_PSS', __name__, template_folder='templates')


@module_nep_pss.route('/MachiningShop', methods=['GET'])
def machining_shop_line():
    line_name = request.args.get('line_name')
    device = request.args.get('device')
    items = {
        'line_name': line_name,
        'time': int(time.time())
    }
    if device == 'mobile':
        tpl_name = 'mobile/machining_shop_line.html'
    else:
        tpl_name = 'machining_shop_line.html'
    return render_template(tpl_name, items=items)


@module_nep_pss.route('/gline', methods=['GET'])
def gline():
    line_name = request.args.get('line_name')
    if line_name != 'Z6':
        line_name = 'G6'
    items = {'line_name': line_name}
    return render_template('gline.html', items=items)


@module_nep_pss.route('/oracle')
def db_link():
    items = SchichtKalenderGrossAnzeige.query.limit(10).all()
    return render_template('test/oracle.html', items=items)


@module_nep_pss.route('/test')
def test():
    # print(time.mktime(time.strptime('2016-09-13 14:18:00', '%Y-%m-%d %H:%M:%S')))
    # print(int(round(time.time())))
    # print('path=>', request.path)
    # print('base_url=>', request.base_url)
    # print('script_root=>', request.script_root)
    # print('url=>', request.url)
    # print('url_root=>', request.url_root)
    ## get data by raw sql
    # from flask import current_app
    # sql = "SELECT prozessid, rtn, akz, COUNT(*) FROM (SELECT dmcode, rtn, prozessid, azeit, akz, statusid, RANK() OVER (PARTITION BY dmcode,prozessid ORDER BY zeitpunkt DESC) rank FROM Als_rc.teilehist WHERE prozessid IN (200,601) and akz in('LP11', 'LP12', 'LP13', 'LP14', 'LP15', 'LP16', 'LP21', 'LP22', 'LP23', 'LP24', 'LP25', 'LP26', 'LP31', 'LP32', 'LP33') AND zeitpunkt   >=TO_DATE('07.12.2016 00:00:00','dd.mm.yyyy hh24:mi:ss')) GROUP BY prozessid, rtn, akz ORDER BY prozessid, rtn"
    # teileData = db.get_engine(current_app, bind='ALS_NEP_Production').execute(sql)
    # for teileItem in teileData:
    #     print('xxxxxxxxxxxxxxxxxxx')
    #     print(teileItem[0])
    #     print(teileItem)

    from app.helper.pss import get_week_day_total_hours

    op = 'AFO580'
    baz = '0C1'
    # db_engine = db.get_engine(current_app, bind='PSS_Archive_Production_Z6')
    db_engine = db.get_engine(current_app, bind='PSS_Archive_Production_G6')
    th = get_week_day_total_hours(db_engine, op, baz, '2018-06-20', 'G6')

    # print('total_hours')
    # print(th)

    return 'current_timestamp:' + str(int(round(time.time()))) + ';script_root:' + request.path


# get current shift parts number
def get_current_production(operation, start_time, end_time, line_name):
    zelle = '1'
    baz = '0C1'
    if line_name == 'Z6':
        if operation == 'AFO010':
            baz = '0S1'
        qry_row = db2.session.query(func.count('*')).filter(
            and_(
                Z6ArchivWorkLog.FERTEINR_OP == operation,
                Z6ArchivWorkLog.FERTEINR_ZN == zelle,
                Z6ArchivWorkLog.FERTEINR_BAZ == baz,
                Z6ArchivWorkLog.VORRICHTUNG >= 0,
                Z6ArchivWorkLog.UEBERLAUF < 99,
                Z6ArchivWorkLog.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
                Z6ArchivWorkLog.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS')
            )).first()
        count_val = qry_row[0]
    else:
        qry_row = db.session.query(func.count('*')).filter(
            and_(
                ArchivWorkLog.FERTEINR_OP == operation,
                ArchivWorkLog.FERTEINR_ZN == zelle,
                ArchivWorkLog.FERTEINR_BAZ == baz,
                ArchivWorkLog.VORRICHTUNG >= 0,
                ArchivWorkLog.UEBERLAUF < 99,
                ArchivWorkLog.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
                ArchivWorkLog.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS')
            )).first()
        count_val = qry_row[0]
    return count_val


def get_timestamp_from_string(time_str, time_format='%Y-%m-%d %H:%M:%S'):
    return time.mktime(time.strptime(time_str, time_format))


def calc_time_lag(start_time_str, end_time_str, time_format='%Y-%m-%d %H:%M:%S'):
    return int(round(
        get_timestamp_from_string(end_time_str, time_format) - get_timestamp_from_string(start_time_str, time_format)))


def calc_forecast_num(current_num, passed_second, total_second):
    return int(current_num / passed_second * total_second) if passed_second > 0 else '-'


def calc_planned_num(target_num, passed_second, total_second):
    return int(target_num / total_second * passed_second) if passed_second > 0 else '-'


# todo 20160930 国庆回来继续
def get_shift_time(date_num, line_name, date_format='%Y%m%d'):
    # # if line_name == 'Z6':
    # #     items = Z6SchichtKalenderGrossAnzeige.query \
    # #         .filter(Z6SchichtKalenderGrossAnzeige.NG6SK_DATUM == date_num) \
    # #         .all()
    # # else:
    # #     items = SchichtKalenderGrossAnzeige.query \
    # #         .filter(SchichtKalenderGrossAnzeige.NG6SK_DATUM == date_num) \
    # #         .all()
    #
    # date_tuple = time.strptime(date_num, '%Y%m%d')
    # date_str = time.strftime('%F 00:00:00', date_tuple)
    # items = SchichtKalender.query \
    #     .filter(and_(SchichtKalender.LINIE_KZ == line_name,
    #                  SchichtKalender.FB_OPERATION == 'AFO010',
    #                  SchichtKalender.DATUM == func.TO_DATE(date_str, 'YYYY-MM-DD HH24:MI:SS'))) \
    #     .all()
    # step 1 : 从 STANDARDSCHICHTMODELLE 表中获取小于等于当天的 SS_ID 最后一值
    # step 2 : 通过 SS_ID 从 STANDARDMODELLE 表中 获取 MD_ID、MODELL_NR、PROD_VON、PROD_BIS、PROG_STUECK
    # step 3 : 通过 MD_ID 从 STANDARDSCHICHTEN 表中 获取 当天使用的 Vorgabe 值
    # step 4 : 组织需要的数据
    items = []
    # do step 1
    # 获取明天的起始时间
    date_tuple = time.strptime(date_num, date_format)
    day_base_str = time.strftime('%Y-%m-%d', date_tuple)
    today_time_stamp = time.mktime(date_tuple)
    tomorrow_time_stamp = today_time_stamp + 3600 * 24
    tomorrow_time_tuple = time.localtime(tomorrow_time_stamp)
    tomorrow_date_str = time.strftime('%F 00:00:00', tomorrow_time_tuple)
    tomorrow_base_str = time.strftime('%Y-%m-%d', tomorrow_time_tuple)
    qry_row = db.session.query(StandARDSchichtModelle.SS_ID).filter(
        and_(StandARDSchichtModelle.LINIE_KZ == line_name,
             StandARDSchichtModelle.GUELTIG_VON < func.TO_DATE(tomorrow_date_str, 'YYYY-MM-DD HH24:MI:SS'))
    ).order_by(desc(StandARDSchichtModelle.SS_ID)).first()
    if qry_row is not None:
        ss_id = qry_row[0]
        # do step 2
        qry_row = db.session.query(StandardModelle).filter(
            and_(StandardModelle.SS_ID == ss_id, StandardModelle.MODELL_NR > 0)
        ).all()
        day_of_week = time.strftime('%w', date_tuple)
        day_of_week = day_of_week if int(day_of_week) > 0 else '7'
        if qry_row is not None:
            modelle_dict = {}
            for row in qry_row:
                md_id = row.MD_ID
                modell_nr = row.MODELL_NR
                modelle_dict[modell_nr] = row
                # do step 3
                schicht_items = db.session.query(StandARDSchichten).filter(
                    and_(
                        StandARDSchichten.MD_ID == md_id,
                        StandARDSchichten.TAG == day_of_week
                    )
                ).all()
                from_time = format_hour_str(row.PROD_VON)
                to_time = format_hour_str(row.PROD_BIS)
                if schicht_items is not None:
                    for schicht_item in schicht_items:
                        start_struct_time = False
                        end_struct_time = False
                        if from_time:
                            start_time = day_base_str + ' ' + format_hour_str(row.PROD_VON)
                            start_struct_time = time.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                        if to_time:
                            if schicht_item.SCHICHT == '3':
                                end_time = tomorrow_base_str + ' ' + format_hour_str(row.PROD_BIS)
                            else:
                                end_time = day_base_str + ' ' + format_hour_str(row.PROD_BIS)
                            end_struct_time = time.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                        item_dict = {
                            'SCHICHT': schicht_item.SCHICHT,
                            'SS_ID': ss_id,
                            'MD_ID': md_id,
                            'MODELL_NR': modell_nr,
                            'SCHICHT_VON': start_struct_time,
                            'SCHICHT_BIS': end_struct_time,
                            'PROG_STUECK': row.PROG_STUECK
                        }
                        items.append(item_dict)
            if line_name == 'G6' and day_of_week == '5':
                schicht_list = []
                for (item_key, item_val) in enumerate(items):
                    if item_val['SCHICHT'] == '1' or item_val['SCHICHT'] == '2':
                        schicht_list.append(item_val['SCHICHT'])
                        # G6 每周五从 5、6 里取数据
                        mid_idx = str(int(item_val['SCHICHT']) + 4)
                        # print('&&&&&&&&&&&&&&&&&&&&&&&&&')
                        # print(mid_idx)
                        if mid_idx in modelle_dict:
                            mid_item = modelle_dict[mid_idx]
                            ########## TMP ##########
                            from_time = format_hour_str(mid_item.PROD_VON)
                            to_time = format_hour_str(mid_item.PROD_BIS)
                            # from_time = format_hour_str('083000')
                            # to_time = format_hour_str('170000')
                            ########## TMP ##########
                            start_struct_time = False
                            end_struct_time = False
                            if from_time:
                                start_time = day_base_str + ' ' + from_time
                                start_struct_time = time.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                            if to_time:
                                end_time = day_base_str + ' ' + to_time
                                end_struct_time = time.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                            item_val['SCHICHT_VON'] = start_struct_time
                            item_val['SCHICHT_BIS'] = end_struct_time
                            ########## TMP ##########
                            item_val['PROG_STUECK'] = mid_item.PROG_STUECK
                            item_val['SOLL_STUECK'] = mid_item.SOLL_STUECK
                            # item_val['PROG_STUECK'] = 0
                            # item_val['SOLL_STUECK'] = 0
                            ########## TMP ##########
                            items[item_key] = item_val
                        else:
                            del items[item_key]

                # 特殊处理，如果SCHICHT的值1或2不存在，但preseting的5，6却有值
                # 需要特殊处理的列表
                special_list = ['5', '6']
                for special_val in special_list:
                    sp_val = str(int(special_val) - 4)
                    if special_val in modelle_dict and sp_val not in schicht_list:
                        sp_dict = {}
                        mid_item = modelle_dict[special_val]
                        from_time = format_hour_str(mid_item.PROD_VON)
                        to_time = format_hour_str(mid_item.PROD_BIS)
                        start_struct_time = False
                        end_struct_time = False
                        if from_time:
                            start_time = day_base_str + ' ' + from_time
                            start_struct_time = time.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                        if to_time:
                            end_time = day_base_str + ' ' + to_time
                            end_struct_time = time.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                        sp_dict['SCHICHT'] = sp_val
                        sp_dict['SCHICHT_VON'] = start_struct_time
                        sp_dict['SCHICHT_BIS'] = end_struct_time
                        sp_dict['PROG_STUECK'] = mid_item.PROG_STUECK
                        sp_dict['SOLL_STUECK'] = mid_item.SOLL_STUECK
                        items.append(sp_dict)
    return items


@module_nep_pss.route('/api/product_info', methods=['GET'])
def product_info():
    from app.helper.util import get_date_str, get_week_first_date_str
    from app.helper.pss import get_production_volume_by_range, get_week_day_total_hours
    resp = {}
    today_date_num = time.strftime("%Y%m%d", time.localtime())
    today_date_str = time.strftime('%Y-%m-%d')
    week_first_day = get_week_first_date_str(today_date_str)
    request_date_str = request.args.get('date')
    line_name = request.args.get('line_name')
    if request_date_str:
        date_num = request_date_str
    else:
        date_num = today_date_num

    if line_name == 'Z6':
        op = 'AFO010'
        baz = '0S1'
        db_engine = db.get_engine(current_app, bind='PSS_Archive_Production_Z6')
    else:
        op = 'AFO580'
        baz = '0C1'
        line_name = 'G6'
        db_engine = db.get_engine(current_app, bind='PSS_Archive_Production_G6')
    current_timestamp = int(round(time.time()))

    if today_date_num == date_num:
        yesterday_date_str = get_date_str(-1, '%Y%m%d')
        yesterday_shift_info_list = get_shift_time(yesterday_date_str, line_name)
        in_yesterday_shift_flag = False
        for yesterday_shift_info in yesterday_shift_info_list:
            yesterday_start_timestamp = time.mktime(yesterday_shift_info['SCHICHT_VON'])
            yesterday_end_timestamp = time.mktime(yesterday_shift_info['SCHICHT_BIS'])
            if yesterday_end_timestamp >= current_timestamp >= yesterday_start_timestamp:
                in_yesterday_shift_flag = True
        if in_yesterday_shift_flag is True:
            items = get_shift_time(yesterday_date_str, line_name)
        else:
            items = get_shift_time(date_num, line_name)
    else:
        items = get_shift_time(date_num, line_name)

    week_first_day_shift_info = []
    for _week_num in range(0, 7):
        week_first_day = get_week_first_date_str(today_date_str, _week_num + 1)
        week_first_day_shift_info = get_shift_time(week_first_day, line_name, '%Y-%m-%d')
        if week_first_day_shift_info:
            break

    week_first_day_shift_1_time = None
    week_first_day_first_shift_num = None
    for week_first_day_shift_item in week_first_day_shift_info:
        if week_first_day_shift_item['SCHICHT_BIS'] and week_first_day_shift_item['SCHICHT_VON']:
            _shift_num = int(week_first_day_shift_item['SCHICHT'])
            if week_first_day_first_shift_num is None or _shift_num < week_first_day_first_shift_num:
                week_first_day_first_shift_num = _shift_num
                week_first_day_shift_1_time = time.strftime('%H:%M:%S', week_first_day_shift_item['SCHICHT_VON'])

    # for item in items:
    #     if item.SCHICHT_BIS != item.SCHICHT_VON:
    #         PROG_STUECK = item.PROG_STUECK
    #         day_of_week = time.strftime('%w')
    #         day_time_str = time.strftime('%F 00:00:00')
    #
    #         # 特殊日期，特殊处理
    #         if day_of_week == '5':
    #             output_val = get_custom_output(day_time_str, line_name)
    #             if output_val > 0:
    #                 PROG_STUECK = output_val
    #
    #         if item.SCHICHT == "1":
    #             resp['StartTime1'] = item.SCHICHT_VON.strftime('%F %T')
    #             resp['EndTime1'] = item.SCHICHT_BIS.strftime('%F %T')
    #
    #             period_end_timestamp = get_timestamp_from_string(resp['EndTime1'])
    #             if current_timestamp < period_end_timestamp:
    #                 period_end_timestamp = current_timestamp
    #             passed_second = int(round(period_end_timestamp - get_timestamp_from_string(resp['StartTime1'])))
    #             passed_second = passed_second if passed_second > 0 else 0
    #
    #             total_second = calc_time_lag(resp['StartTime1'], resp['EndTime1'])
    #
    #             resp['S1'] = item.SCHICHT_VON.strftime('%H:%M')
    #             resp['E1'] = item.SCHICHT_BIS.strftime('%H:%M')
    #             resp['TargetOutput1'] = PROG_STUECK
    #             resp['TargetInput1'] = PROG_STUECK
    #             resp['CurrentOutput1'] = get_current_production('AFO580', resp['StartTime1'], resp['EndTime1'],
    #                                                             line_name)
    #             resp['CurrentInput1'] = get_current_production('AFO010', resp['StartTime1'], resp['EndTime1'],
    #                                                            line_name)
    #             resp['ForecastOutput1'] = calc_forecast_num(resp['CurrentOutput1'], passed_second, total_second)
    #             resp['ForecastInput1'] = calc_forecast_num(resp['CurrentInput1'], passed_second, total_second)
    #             resp['PlannedOutput1'] = calc_planned_num(resp['TargetOutput1'], passed_second, total_second)
    #             resp['PlannedInput1'] = calc_planned_num(resp['TargetInput1'], passed_second, total_second)
    #         elif item.SCHICHT == "2":
    #             resp['StartTime2'] = item.SCHICHT_VON.strftime('%F %T')
    #             resp['EndTime2'] = item.SCHICHT_BIS.strftime('%F %T')
    #
    #             period_end_timestamp = get_timestamp_from_string(resp['EndTime2'])
    #             if current_timestamp < period_end_timestamp:
    #                 period_end_timestamp = current_timestamp
    #             passed_second = int(round(period_end_timestamp - get_timestamp_from_string(resp['StartTime2'])))
    #             passed_second = passed_second if passed_second > 0 else 0
    #
    #             total_second = calc_time_lag(resp['StartTime2'], resp['EndTime2'])
    #
    #             resp['S2'] = item.SCHICHT_VON.strftime('%H:%M')
    #             resp['E2'] = item.SCHICHT_BIS.strftime('%H:%M')
    #             resp['TargetOutput2'] = PROG_STUECK
    #             resp['TargetInput2'] = PROG_STUECK
    #             resp['CurrentOutput2'] = get_current_production('AFO580', resp['StartTime2'], resp['EndTime2'],
    #                                                             line_name)
    #             resp['CurrentInput2'] = get_current_production('AFO010', resp['StartTime2'], resp['EndTime2'],
    #                                                            line_name)
    #             resp['ForecastOutput2'] = calc_forecast_num(resp['CurrentOutput2'], passed_second, total_second)
    #             resp['ForecastInput2'] = calc_forecast_num(resp['CurrentInput2'], passed_second, total_second)
    #             resp['PlannedOutput2'] = calc_planned_num(resp['TargetOutput2'], passed_second, total_second)
    #             resp['PlannedInput2'] = calc_planned_num(resp['TargetInput2'], passed_second, total_second)
    #         elif item.SCHICHT == "3":
    #             resp['StartTime3'] = item.SCHICHT_VON.strftime('%F %T')
    #             resp['EndTime3'] = item.SCHICHT_BIS.strftime('%F %T')
    #
    #             period_end_timestamp = get_timestamp_from_string(resp['EndTime3'])
    #             if current_timestamp < period_end_timestamp:
    #                 period_end_timestamp = current_timestamp
    #             passed_second = int(round(period_end_timestamp - get_timestamp_from_string(resp['StartTime3'])))
    #             passed_second = passed_second if passed_second > 0 else 0
    #
    #             total_second = calc_time_lag(resp['StartTime3'], resp['EndTime3'])
    #
    #             resp['S3'] = item.SCHICHT_VON.strftime('%H:%M')
    #             resp['E3'] = item.SCHICHT_BIS.strftime('%H:%M')
    #             resp['TargetOutput3'] = PROG_STUECK
    #             resp['TargetInput3'] = PROG_STUECK
    #             resp['CurrentOutput3'] = get_current_production('AFO580', resp['StartTime3'], resp['EndTime3'],
    #                                                             line_name)
    #             resp['CurrentInput3'] = get_current_production('AFO010', resp['StartTime3'], resp['EndTime3'],
    #                                                            line_name)
    #             resp['ForecastOutput3'] = calc_forecast_num(resp['CurrentOutput3'], passed_second, total_second)
    #             resp['ForecastInput3'] = calc_forecast_num(resp['CurrentInput3'], passed_second, total_second)
    #             resp['PlannedOutput3'] = calc_planned_num(resp['TargetOutput3'], passed_second, total_second)
    #             resp['PlannedInput3'] = calc_planned_num(resp['TargetInput3'], passed_second, total_second)

    shift_1_time = None
    for item in items:
        if item['SCHICHT_BIS'] and item['SCHICHT_VON']:
            prog_stueck = item['PROG_STUECK']
            soll_stueck = item['SOLL_STUECK'] if 'SOLL_STUECK' in item else prog_stueck
            if item['SCHICHT'] == "1":
                resp['StartTime1'] = time.strftime('%F %T', item['SCHICHT_VON'])
                resp['EndTime1'] = time.strftime('%F %T', item['SCHICHT_BIS'])
                shift_1_time = time.strftime('%H:%M:%S', item['SCHICHT_VON'])
                period_end_timestamp = get_timestamp_from_string(resp['EndTime1'])
                if current_timestamp < period_end_timestamp:
                    period_end_timestamp = current_timestamp
                passed_second = int(round(period_end_timestamp - get_timestamp_from_string(resp['StartTime1'])))
                passed_second = passed_second if passed_second > 0 else 0

                total_second = calc_time_lag(resp['StartTime1'], resp['EndTime1'])

                resp['S1'] = time.strftime('%H:%M', item['SCHICHT_VON'])
                resp['E1'] = time.strftime('%H:%M', item['SCHICHT_BIS'])
                resp['TargetOutput1'] = prog_stueck
                resp['TargetInput1'] = soll_stueck
                resp['CurrentOutput1'] = get_current_production('AFO580', resp['StartTime1'], resp['EndTime1'],
                                                                line_name)
                resp['CurrentInput1'] = get_current_production('AFO010', resp['StartTime1'], resp['EndTime1'],
                                                               line_name)
                resp['ForecastOutput1'] = calc_forecast_num(resp['CurrentOutput1'], passed_second, total_second)
                resp['ForecastInput1'] = calc_forecast_num(resp['CurrentInput1'], passed_second, total_second)
                resp['PlannedOutput1'] = calc_planned_num(resp['TargetOutput1'], passed_second, total_second)
                resp['PlannedInput1'] = calc_planned_num(resp['TargetInput1'], passed_second, total_second)
            elif item['SCHICHT'] == "2":
                resp['StartTime2'] = time.strftime('%F %T', item['SCHICHT_VON'])
                resp['EndTime2'] = time.strftime('%F %T', item['SCHICHT_BIS'])

                period_end_timestamp = get_timestamp_from_string(resp['EndTime2'])
                if current_timestamp < period_end_timestamp:
                    period_end_timestamp = current_timestamp
                passed_second = int(round(period_end_timestamp - get_timestamp_from_string(resp['StartTime2'])))
                passed_second = passed_second if passed_second > 0 else 0

                total_second = calc_time_lag(resp['StartTime2'], resp['EndTime2'])

                resp['S2'] = time.strftime('%H:%M', item['SCHICHT_VON'])
                resp['E2'] = time.strftime('%H:%M', item['SCHICHT_BIS'])
                resp['TargetOutput2'] = prog_stueck
                resp['TargetInput2'] = soll_stueck
                resp['CurrentOutput2'] = get_current_production('AFO580', resp['StartTime2'], resp['EndTime2'],
                                                                line_name)
                resp['CurrentInput2'] = get_current_production('AFO010', resp['StartTime2'], resp['EndTime2'],
                                                               line_name)
                resp['ForecastOutput2'] = calc_forecast_num(resp['CurrentOutput2'], passed_second, total_second)
                resp['ForecastInput2'] = calc_forecast_num(resp['CurrentInput2'], passed_second, total_second)
                resp['PlannedOutput2'] = calc_planned_num(resp['TargetOutput2'], passed_second, total_second)
                resp['PlannedInput2'] = calc_planned_num(resp['TargetInput2'], passed_second, total_second)
            elif item['SCHICHT'] == "3":
                resp['StartTime3'] = time.strftime('%F %T', item['SCHICHT_VON'])
                resp['EndTime3'] = time.strftime('%F %T', item['SCHICHT_BIS'])
                period_end_timestamp = get_timestamp_from_string(resp['EndTime3'])
                if current_timestamp < period_end_timestamp:
                    period_end_timestamp = current_timestamp
                passed_second = int(round(period_end_timestamp - get_timestamp_from_string(resp['StartTime3'])))
                passed_second = passed_second if passed_second > 0 else 0
                total_second = calc_time_lag(resp['StartTime3'], resp['EndTime3'])
                resp['S3'] = time.strftime('%H:%M', item['SCHICHT_VON'])
                resp['E3'] = time.strftime('%H:%M', item['SCHICHT_BIS'])
                resp['TargetOutput3'] = prog_stueck
                resp['TargetInput3'] = soll_stueck
                resp['CurrentOutput3'] = get_current_production('AFO580', resp['StartTime3'], resp['EndTime3'],
                                                                line_name)
                resp['CurrentInput3'] = get_current_production('AFO010', resp['StartTime3'], resp['EndTime3'],
                                                               line_name)
                resp['ForecastOutput3'] = calc_forecast_num(resp['CurrentOutput3'], passed_second, total_second)
                resp['ForecastInput3'] = calc_forecast_num(resp['CurrentInput3'], passed_second, total_second)
                resp['PlannedOutput3'] = calc_planned_num(resp['TargetOutput3'], passed_second, total_second)
                resp['PlannedInput3'] = calc_planned_num(resp['TargetInput3'], passed_second, total_second)

    if shift_1_time is not None:
        # import datetime
        week_shift_1_time = week_first_day + ' ' + week_first_day_shift_1_time
        # d = datetime.datetime.now()
        # week_num = d.weekday()
        # shift_1_time_str = today_date_str + ' ' + shift_1_time
        # shift_1_time_strtime_tuple = time.strptime(shift_1_time_str, '%Y-%m-%d %H:%M:%S')
        # shift_1_timestamp = time.mktime(shift_1_time_strtime_tuple)
        # current_timestamp = time.mktime(time.localtime())
        # today_passed_hour = (current_timestamp - shift_1_timestamp) / 3600
        week_total_hour = get_week_day_total_hours(db_engine, op, baz, today_date_str, line_name)
        # print('@@@@@@')
        # print(line_name)
        production_volume_of_current_week = get_production_volume_by_range(db_engine, 'AFO580', '0C1',
                                                                           week_shift_1_time)
        if week_total_hour > 0:
            resp['weekLineRate'] = round(production_volume_of_current_week / week_total_hour, 1)
        else:
            resp['weekLineRate'] = ''
    return json.dumps(resp)


@module_nep_pss.route('/api/history', methods=['GET'])
def data_history():
    line_name = request.args.get('line_name')
    items = {
        'line_name': line_name if line_name != 'T6' else 'Z6'
    }
    return render_template('history_data.html', items=items)


# 获取工位的状态值
def get_operation_state(operation_tuple, start_time, end_time, line_name):
    if line_name == 'Z6':
        row_list = Z6ArchivAKTBDEMA.query \
            .filter(and_(Z6ArchivAKTBDEMA.QUELLE_OP.in_(operation_tuple),
                         Z6ArchivAKTBDEMA.ZEITSTEMPEL >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
                         Z6ArchivAKTBDEMA.ZEITSTEMPEL < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))).all()
    else:
        row_list = ArchivAKTBDEMA.query \
            .filter(and_(ArchivAKTBDEMA.QUELLE_OP.in_(operation_tuple),
                         ArchivAKTBDEMA.ZEITSTEMPEL >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
                         ArchivAKTBDEMA.ZEITSTEMPEL < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))).all()
    return row_list


def get_operation_value(operation, zelle, baz, start_time, end_time, line_name):
    # operation_str = operation + '/' + zelle + '/' + baz
    if line_name == 'Z6':
        # # sub_num = Z6NG6OOSEREIGNISSE.query \
        # #     .filter(and_(Z6NG6OOSEREIGNISSE.OPERATION == operation,
        # #                  Z6NG6OOSEREIGNISSE.ZELLE == zelle,
        # #                  Z6NG6OOSEREIGNISSE.BAZ == baz,
        # #                  Z6NG6OOSEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        # #                  Z6NG6OOSEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))) \
        # #     .distinct(Z6NG6OOSEREIGNISSE.NR_J) \
        # #     .count()
        # # # if operation == 'AFO520' and zelle == '1' and (baz == '002'):
        # # #     op_num = Z6ArchivWorkLog.query \
        # # #         .filter(and_(Z6ArchivWorkLog.OPERATION == operation,
        # # #                      Z6ArchivWorkLog.ZELLE == zelle,
        # # #                      Z6ArchivWorkLog.BAZ == baz,
        # # #                      Z6ArchivWorkLog.UEBERLAUF == 0,
        # # #                      Z6ArchivWorkLog.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        # # #                      Z6ArchivWorkLog.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))) \
        # # #         .count()
        # # #     op_num = int(op_num) - int(sub_num)
        # # # else:
        # # #     op_num = Z6NG6EINZELEREIGNISSE.query \
        # # #         .filter(and_(Z6NG6EINZELEREIGNISSE.OPERATION == operation,
        # # #                      Z6NG6EINZELEREIGNISSE.ZELLE == zelle,
        # # #                      Z6NG6EINZELEREIGNISSE.BAZ == baz,
        # # #                      Z6NG6EINZELEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        # # #                      Z6NG6EINZELEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))) \
        # # #         .distinct(Z6NG6EINZELEREIGNISSE.NR_J) \
        # # #         .count()
        # # #     op_num = int(op_num) + int(sub_num)
        #
        # # op_num = Z6NG6EINZELEREIGNISSE.query \
        # #     .filter(and_(Z6NG6EINZELEREIGNISSE.OPERATION == operation,
        # #                  Z6NG6EINZELEREIGNISSE.ZELLE == zelle,
        # #                  Z6NG6EINZELEREIGNISSE.BAZ == baz,
        # #                  Z6NG6EINZELEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        # #                  Z6NG6EINZELEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))) \
        # #     .distinct(Z6NG6EINZELEREIGNISSE.NR_J) \
        # #     .count()
        # # op_num = int(op_num) + int(sub_num)
        #
        # qry_row = db2.session.query(func.count(distinct(Z6NG6OOSEREIGNISSE.SACHNR_ZB))) \
        #     .filter(and_(Z6NG6OOSEREIGNISSE.OPERATION == operation,
        #                  Z6NG6OOSEREIGNISSE.ZELLE == zelle,
        #                  Z6NG6OOSEREIGNISSE.BAZ == baz,
        #                  Z6NG6OOSEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        #                  Z6NG6OOSEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))) \
        #     .distinct(Z6NG6OOSEREIGNISSE.NR_J) \
        #     .first()
        # sub_num = qry_row[0]
        #
        # special_tuple = (
        #     'AFO100/1/007',
        #     'AFO100/2/007',
        #     'AFO200/1/005',
        #     'AFO200/2/005',
        #     'AFO425/1/001',
        #     'AFO440/1/003',
        #     'AFO440/1/004',
        #     'AFO440/1/005',
        #     'AFO540/1/002',
        #     'AFO540/1/003',
        #     'AFO600/2/002',
        #     'AFO600/2/003',
        #     'AFO600/2/004',
        #     'AFO600/2/005',
        #     'AFO600/1/001',
        #     'AFO600/1/002',
        #     'AFO600/1/003',
        #     'AFO600/1/004',
        #     'AFO600/1/005'
        # )
        #
        # if operation_str in special_tuple:
        #     qry_row = db.session.query(func.count(distinct(Z6NG6EINZELEREIGNISSE.NR_J))).filter(
        #         and_(Z6NG6EINZELEREIGNISSE.OPERATION == operation,
        #              Z6NG6EINZELEREIGNISSE.ZELLE == zelle,
        #              Z6NG6EINZELEREIGNISSE.BAZ == baz,
        #              Z6NG6EINZELEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        #              Z6NG6EINZELEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))).first()
        #     op_num = qry_row[0]
        # else:
        #     qry_row = db2.session.query(func.count('*')).filter(
        #         and_(
        #             Z6ArchivWorkLog.OPERATION == operation,
        #             Z6ArchivWorkLog.ZELLE == zelle,
        #             Z6ArchivWorkLog.BAZ == baz,
        #             Z6ArchivWorkLog.VORRICHTUNG >= 0,
        #             Z6ArchivWorkLog.UEBERLAUF < 99,
        #             Z6ArchivWorkLog.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        #             Z6ArchivWorkLog.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS')
        #         )).first()
        #     op_num = qry_row[0]
        # op_num = int(op_num) + int(sub_num)
        qry_row = db2.session.query(func.count('*')).filter(
            and_(
                Z6ArchivWorkLog.FERTEINR_OP == operation,
                Z6ArchivWorkLog.FERTEINR_ZN == zelle,
                Z6ArchivWorkLog.FERTEINR_BAZ == baz,
                Z6ArchivWorkLog.VORRICHTUNG >= 0,
                Z6ArchivWorkLog.UEBERLAUF < 99,
                Z6ArchivWorkLog.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
                Z6ArchivWorkLog.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS')
            )).first()
        op_num = qry_row[0]
    else:
        # # sub_num = NG6OOSEREIGNISSE.query \
        # #     .filter(and_(NG6OOSEREIGNISSE.OPERATION == operation,
        # #                  NG6OOSEREIGNISSE.ZELLE == zelle,
        # #                  NG6OOSEREIGNISSE.BAZ == baz,
        # #                  NG6OOSEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        # #                  NG6OOSEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))) \
        # #     .distinct(NG6OOSEREIGNISSE.NR_J) \
        # #     .count()
        # #
        # # if operation == 'AFO560' and zelle == '1' and (baz == '003' or baz == '004'):
        # #     op_num = ArchivWorkLog.query \
        # #         .filter(and_(ArchivWorkLog.OPERATION == operation,
        # #                      ArchivWorkLog.ZELLE == zelle,
        # #                      ArchivWorkLog.BAZ == baz,
        # #                      ArchivWorkLog.UEBERLAUF == 0,
        # #                      ArchivWorkLog.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        # #                      ArchivWorkLog.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))) \
        # #         .count()
        # #     op_num = int(op_num) - int(sub_num)
        # # else:
        # #     op_num = NG6EINZELEREIGNISSE.query \
        # #         .filter(and_(NG6EINZELEREIGNISSE.OPERATION == operation,
        # #                      NG6EINZELEREIGNISSE.ZELLE == zelle,
        # #                      NG6EINZELEREIGNISSE.BAZ == baz,
        # #                      NG6EINZELEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        # #                      NG6EINZELEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))) \
        # #         .distinct(NG6EINZELEREIGNISSE.NR_J) \
        # #         .count()
        # #     op_num = int(op_num) + int(sub_num)
        #
        # # qry_row = db.session.query(func.count(distinct(NG6OOSEREIGNISSE.SACHNR_ZB))).filter(
        # #     and_(
        # #         NG6OOSEREIGNISSE.OPERATION == operation,
        # #         NG6OOSEREIGNISSE.ZELLE == zelle,
        # #         NG6OOSEREIGNISSE.BAZ == baz,
        # #         NG6OOSEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        # #         NG6OOSEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS')
        # #     )).first()
        # # sub_num = qry_row[0]
        # special_tuple = (
        #     # 'AFO010/1/0C1',
        #     'AFO180/1/007',
        #     'AFO180/1/008',
        #     'AFO180/2/007',
        #     'AFO180/2/008',
        #     'AFO320/1/002',
        #     'AFO320/1/003',
        #     'AFO560/1/001',
        #     'AFO600/1/001',
        #     'AFO600/1/002',
        #     'AFO600/1/003',
        #     'AFO600/1/004',
        #     'AFO600/1/005'
        # )
        # if operation_str in special_tuple:
        #     qry_row = db.session.query(func.count(distinct(NG6EINZELEREIGNISSE.NR_J))).filter(
        #         and_(NG6EINZELEREIGNISSE.OPERATION == operation,
        #              NG6EINZELEREIGNISSE.ZELLE == zelle,
        #              NG6EINZELEREIGNISSE.BAZ == baz,
        #              NG6EINZELEREIGNISSE.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        #              NG6EINZELEREIGNISSE.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS'))).first()
        #     op_num = qry_row[0]
        # else:
        #     if operation_str == 'AFO010/1/0C1':
        #         operation = 'AFO030'
        #     qry_row = db.session.query(func.count('*')).filter(
        #         and_(
        #             ArchivWorkLog.OPERATION == operation,
        #             ArchivWorkLog.ZELLE == zelle,
        #             ArchivWorkLog.BAZ == baz,
        #             ArchivWorkLog.VORRICHTUNG >= 0,
        #             ArchivWorkLog.UEBERLAUF < 99,
        #             ArchivWorkLog.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
        #             ArchivWorkLog.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS')
        #         )).first()
        #     op_num = qry_row[0]
        qry_row = db.session.query(func.count('*')).filter(
            and_(
                ArchivWorkLog.FERTEINR_OP == operation,
                ArchivWorkLog.FERTEINR_ZN == zelle,
                ArchivWorkLog.FERTEINR_BAZ == baz,
                ArchivWorkLog.VORRICHTUNG >= 0,
                ArchivWorkLog.UEBERLAUF < 99,
                ArchivWorkLog.BEARB_DATUM >= func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS'),
                ArchivWorkLog.BEARB_DATUM < func.TO_DATE(end_time, 'YYYY-MM-DD HH24:MI:SS')
            )).first()
        op_num = qry_row[0]
    return op_num


# def get_operation_value(operation, zelle, baz, start_time, end_time, line_name):
#     op_num = 0
#     row_list = StueckZAHLProSchicht.query \
#         .filter(and_(StueckZAHLProSchicht.LINIE_KZ == line_name,
#                      StueckZAHLProSchicht.FB_OPERATION == operation,
#                      StueckZAHLProSchicht.FMA_ZELLE == zelle,
#                      StueckZAHLProSchicht.FMA_BAZ == baz,
#                      StueckZAHLProSchicht.DATUM == func.TO_DATE(start_time, 'YYYY-MM-DD HH24:MI:SS')
#                      )
#                 ) \
#         .all()
#     if row_list:
#         for row in row_list:
#             op_num = op_num + row.STUECK
#     return op_num


@module_nep_pss.route('/api/line_data', methods=['GET'])
def cache_line_data():
    from app.helper.util import get_date_str
    from app.helper.pss import get_shift_time_range, get_message_class, convert_to_shift_hour
    line_name = request.args.get('line_name')

    g6_tuple = (
        'AFO010',
        'AFO080',
        'AFO120',
        'AFO130',
        'AFO140',
        'AFO160',
        'AFO180',
        'AFO200',
        'AFO300',
        'AFO320',
        'AFO400',
        'AFO410',
        'AFO420',
        'AFO440',
        'AFO500',
        'AFO520',
        'AFO560',
        'AFO600'
    )

    g6_op_dict = {
        'AFO010/1/0S1': {'OPERATION': 'AFO010', 'ZELLE': '1', 'BAZ': '0S1', 'flag': 0, 'value': 0, 'title': ''},
        'AFO010/1/0C1': {'OPERATION': 'AFO010', 'ZELLE': '1', 'BAZ': '0C1', 'flag': 0, 'value': 0, 'title': ''},
        'AFO080/1/001': {'OPERATION': 'AFO080', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/001': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/002': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/003': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/004': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/005': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/006': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/007': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/008': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO120/1/0S1': {'OPERATION': 'AFO120', 'ZELLE': '1', 'BAZ': '0S1', 'flag': 0, 'value': 0, 'title': ''},
        'AFO130/1/001': {'OPERATION': 'AFO130', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO130/1/002': {'OPERATION': 'AFO130', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/001': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/002': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/003': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/004': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/005': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/006': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/007': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/008': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/0S1': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '0S1', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/001': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/002': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/003': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/004': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/005': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/006': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/007': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/008': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/009': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '009', 'flag': 0, 'value': 0, 'title': ''},
        'AFO160/1/0S1': {'OPERATION': 'AFO160', 'ZELLE': '1', 'BAZ': '0S1', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/001': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/002': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/003': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/004': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/005': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/006': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/007': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/008': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/009': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '009', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/1/0S1': {'OPERATION': 'AFO180', 'ZELLE': '1', 'BAZ': '0S1', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/001': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/002': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/003': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/004': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/005': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/006': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/007': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/008': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO180/2/009': {'OPERATION': 'AFO180', 'ZELLE': '2', 'BAZ': '009', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/001': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/002': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/003': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/004': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/005': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/006': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/001': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO320/1/001': {'OPERATION': 'AFO320', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO320/1/002': {'OPERATION': 'AFO320', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO320/1/003': {'OPERATION': 'AFO320', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/001': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/002': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/003': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO410/1/001': {'OPERATION': 'AFO410', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/1/001': {'OPERATION': 'AFO420', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/1/002': {'OPERATION': 'AFO420', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/1/003': {'OPERATION': 'AFO420', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO440/1/001': {'OPERATION': 'AFO440', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/001': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/002': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/003': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/0S1': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '0S1', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/1/001': {'OPERATION': 'AFO520', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/1/002': {'OPERATION': 'AFO520', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/1/003': {'OPERATION': 'AFO520', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/1/004': {'OPERATION': 'AFO520', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/2/001': {'OPERATION': 'AFO520', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/2/002': {'OPERATION': 'AFO520', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/2/003': {'OPERATION': 'AFO520', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/2/004': {'OPERATION': 'AFO520', 'ZELLE': '2', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO560/1/0S1': {'OPERATION': 'AFO560', 'ZELLE': '1', 'BAZ': '0S1', 'flag': 0, 'value': 0, 'title': ''},
        'AFO560/1/001': {'OPERATION': 'AFO560', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO560/1/003': {'OPERATION': 'AFO560', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO560/1/004': {'OPERATION': 'AFO560', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/001': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/002': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/003': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/004': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/005': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/006': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/0S1': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '0S1', 'flag': 0, 'value': 0, 'title': ''},
    }

    z6_tuple = (
        'AFO100',
        'AFO140',
        'AFO145',
        'AFO200',
        'AFO240',
        'AFO245',
        'AFO300',
        'AFO400',
        'AFO420',
        'AFO425',
        'AFO440',
        'AFO500',
        'AFO520',
        'AFO522',
        'AFO540',
        'AFO544',
        'AFO560',
        'AFO600'
    )

    z6_op_dict = {
        'AFO100/1/001': {'OPERATION': 'AFO100', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/1/002': {'OPERATION': 'AFO100', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/1/003': {'OPERATION': 'AFO100', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/1/004': {'OPERATION': 'AFO100', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/1/005': {'OPERATION': 'AFO100', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/1/006': {'OPERATION': 'AFO100', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/1/007': {'OPERATION': 'AFO100', 'ZELLE': '1', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/2/002': {'OPERATION': 'AFO100', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/2/003': {'OPERATION': 'AFO100', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/2/004': {'OPERATION': 'AFO100', 'ZELLE': '2', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/2/005': {'OPERATION': 'AFO100', 'ZELLE': '2', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/2/006': {'OPERATION': 'AFO100', 'ZELLE': '2', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO100/2/007': {'OPERATION': 'AFO100', 'ZELLE': '2', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/1/001': {'OPERATION': 'AFO140', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO140/2/001': {'OPERATION': 'AFO140', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO145/1/001': {'OPERATION': 'AFO145', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/001': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/002': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/003': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/004': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/1/005': {'OPERATION': 'AFO200', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/2/001': {'OPERATION': 'AFO200', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/2/002': {'OPERATION': 'AFO200', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/2/003': {'OPERATION': 'AFO200', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/2/004': {'OPERATION': 'AFO200', 'ZELLE': '2', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO200/2/005': {'OPERATION': 'AFO200', 'ZELLE': '2', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO240/1/001': {'OPERATION': 'AFO240', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO240/1/002': {'OPERATION': 'AFO240', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO245/1/001': {'OPERATION': 'AFO245', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/001': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/002': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/003': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/004': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/005': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/006': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/007': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/1/008': {'OPERATION': 'AFO300', 'ZELLE': '1', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/2/001': {'OPERATION': 'AFO300', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/2/002': {'OPERATION': 'AFO300', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/2/003': {'OPERATION': 'AFO300', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/2/004': {'OPERATION': 'AFO300', 'ZELLE': '2', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO300/2/005': {'OPERATION': 'AFO300', 'ZELLE': '2', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/001': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/002': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/003': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/004': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/005': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/006': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/007': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/1/008': {'OPERATION': 'AFO400', 'ZELLE': '1', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/2/001': {'OPERATION': 'AFO400', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/2/002': {'OPERATION': 'AFO400', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO400/2/003': {'OPERATION': 'AFO400', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/1/001': {'OPERATION': 'AFO420', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/1/002': {'OPERATION': 'AFO420', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/1/003': {'OPERATION': 'AFO420', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/1/004': {'OPERATION': 'AFO420', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/2/001': {'OPERATION': 'AFO420', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/2/002': {'OPERATION': 'AFO420', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/2/003': {'OPERATION': 'AFO420', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO420/2/004': {'OPERATION': 'AFO420', 'ZELLE': '2', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO425/1/001': {'OPERATION': 'AFO425', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO440/1/001': {'OPERATION': 'AFO440', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO440/1/002': {'OPERATION': 'AFO440', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO440/1/003': {'OPERATION': 'AFO440', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO440/1/004': {'OPERATION': 'AFO440', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO440/1/005': {'OPERATION': 'AFO440', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/001': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/002': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/003': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/004': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/005': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/006': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/007': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '007', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/1/008': {'OPERATION': 'AFO500', 'ZELLE': '1', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/2/001': {'OPERATION': 'AFO500', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/2/002': {'OPERATION': 'AFO500', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/2/003': {'OPERATION': 'AFO500', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/2/004': {'OPERATION': 'AFO500', 'ZELLE': '2', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/2/005': {'OPERATION': 'AFO500', 'ZELLE': '2', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/2/006': {'OPERATION': 'AFO500', 'ZELLE': '2', 'BAZ': '006', 'flag': 0, 'value': 0, 'title': ''},
        'AFO500/2/008': {'OPERATION': 'AFO500', 'ZELLE': '2', 'BAZ': '008', 'flag': 0, 'value': 0, 'title': ''},
        'AFO520/1/001': {'OPERATION': 'AFO520', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO522/1/002': {'OPERATION': 'AFO522', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO522/1/003': {'OPERATION': 'AFO522', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO540/1/001': {'OPERATION': 'AFO540', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO540/1/002': {'OPERATION': 'AFO540', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO540/1/003': {'OPERATION': 'AFO540', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO544/1/001': {'OPERATION': 'AFO544', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO544/1/002': {'OPERATION': 'AFO544', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO544/1/003': {'OPERATION': 'AFO544', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO560/1/001': {'OPERATION': 'AFO560', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO560/1/002': {'OPERATION': 'AFO560', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/001': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/002': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/003': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/004': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/1/005': {'OPERATION': 'AFO600', 'ZELLE': '1', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/2/001': {'OPERATION': 'AFO600', 'ZELLE': '2', 'BAZ': '001', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/2/002': {'OPERATION': 'AFO600', 'ZELLE': '2', 'BAZ': '002', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/2/003': {'OPERATION': 'AFO600', 'ZELLE': '2', 'BAZ': '003', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/2/004': {'OPERATION': 'AFO600', 'ZELLE': '2', 'BAZ': '004', 'flag': 0, 'value': 0, 'title': ''},
        'AFO600/2/005': {'OPERATION': 'AFO600', 'ZELLE': '2', 'BAZ': '005', 'flag': 0, 'value': 0, 'title': ''}
    }

    if line_name == 'Z6':
        op_tuple = z6_tuple
        op_dict = z6_op_dict
    else:
        line_name = 'G6'
        op_tuple = g6_tuple
        op_dict = g6_op_dict

    event_num_dict = {
        '1': [8, 9, 11, 15, 21, 22, 25, 33, 34, 41, 70],
        '2': [31, 35],
        '3': [19, 44],
        '4': [20, 43],
        '5': [1, 18, 23, 39, 37, 38, 40, 42, 52, 69, 71, 74],
        '6': [4, 64, 68],
        '7': [16, 46, 17, 45, 24],
        '8': [63, 72],
        '9': [36, 47, 48, 49, 50, 51],
        '10': [2, 5, 6, 7, 10, 12, 13, 14, 65, 66, 67],
        '12': [26]
    }

    start_time_str = time.strftime('%F 00:00:00')
    end_time_str = time.strftime('%F 00:00:00', time.localtime(int(time.time()) + 3600 * 24))

    row_list = get_operation_state(op_tuple, start_time_str, end_time_str, line_name)

    for row in row_list:
        aktgrund = row.AKTGRUND
        operation_idx = row.QUELLE_OP + '/' + row.QUELLE_ZN + '/' + row.QUELLE_BAZ
        if operation_idx in op_dict.keys():
            for (eventKey, eventNum) in event_num_dict.items():
                if aktgrund in eventNum:
                    op_dict[operation_idx]['flag'] = eventKey
                    op_dict[operation_idx]['title'] = get_message_class(
                        aktgrund
                    ) + ' since ' + convert_to_shift_hour(
                        row.ZEITSTEMPEL.strftime('%F %T')
                    ) + ' hrs.'

    date_num = time.strftime("%Y%m%d", time.localtime())
    items = get_shift_time(date_num, line_name)

    shift_time_range = get_shift_time_range(items)
    start_time_str = shift_time_range['start_time_str']
    end_time_str = shift_time_range['end_time_str']

    # 如果当前的时间不在当时的班次信息里，应该取前一天的班次
    if start_time_str == '':
        date_num = get_date_str(-1, '%Y%m%d')
        items = get_shift_time(date_num, line_name)
        shift_time_range = get_shift_time_range(items)
        start_time_str = shift_time_range['start_time_str']
        end_time_str = shift_time_range['end_time_str']

    for (opKey, opItem) in op_dict.items():
        op_dict[opKey]['value'] = get_operation_value(
            opItem['OPERATION'],
            opItem['ZELLE'],
            opItem['BAZ'],
            start_time_str,
            end_time_str,
            line_name
        )
    content = json.dumps(op_dict)
    return content


@module_nep_pss.route('/api/system_info')
def get_system_base_info():
    import psutil
    import time
    info_dict = dict()
    info_dict['cpu_percent'] = psutil.cpu_percent(1)
    vir_mem = psutil.virtual_memory()
    info_dict['mem_percent'] = vir_mem.percent
    info_dict['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    info_dict['timestamp'] = int(time.time() * 1000)
    return jsonify(info_dict)


# def get_custom_output(time_str, line_name):
#     output_val = 0
#     model_num = '5'
#     qry_row = db.session.query(StandARDSchichtModelle.SS_ID).filter(
#         and_(StandARDSchichtModelle.LINIE_KZ == line_name,
#              StandARDSchichtModelle.GUELTIG_VON == func.TO_DATE(time_str, 'YYYY-MM-DD HH24:MI:SS'))).first()
#
#     if qry_row is not None:
#         ss_id = qry_row[0]
#         qry_row = db.session.query(StandardModelle.PROG_STUECK).filter(
#             and_(StandardModelle.SS_ID == ss_id,
#                  StandardModelle.MODELL_NR == model_num)
#         ).first()
#         if qry_row[0]:
#             output_val = qry_row[0]
#     return output_val


def format_hour_str(hour_str):
    return hour_str[0:2] + ':' + hour_str[2:4] + ':' + hour_str[4:6] if hour_str is not None else False
